<template xmlns:el-col="http://www.w3.org/1999/html">
  <div id="addCreativeTags">
    <basic-container v-loading="loadingbut">
      <div style="display: flex;justify-content: space-between">
        <el-radio-group v-model="activeName" style="margin-bottom: 30px;" size="mini">
          <el-radio-button label="tag">标签配置</el-radio-button>
          <el-radio-button label="template" v-show="!roles.administrator">模板配置</el-radio-button>
        </el-radio-group>
        <el-button icon="el-icon-close"
                   @click.native="closeWindow"
                   type="text"
                   style="z-index: 100;position: absolute;top: 60px;right: 40px;font-size: 24px;color: #999">
        </el-button>
      </div>
      <div class="tag-page" v-if="activeName==='tag'">
        <tag-card label="标签分组">
          <beetles-tree-list
            @click="onClick"
            @change-name="onChangeName"
            @delete-node="onDel"
            @add-node="onAddNode"
            @on-node-change="OnNodeChange"
            :model="data1"
            default-tree-node-name="new node666"
            default-leaf-node-name="new leaf"
            v-bind:default-expanded="false"
          >
            <template v-slot:leafNameDisplay="slotProps">
                <span>
                  {{ slotProps.model.name }} <span class="muted"></span>
                </span>
            </template>
          </beetles-tree-list>
        </tag-card>
        <tag-card v-if="currentNode!=null" label="标签" class="body-right">
          <div slot="header" class="right-path">
            <span>当前路径：</span>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :key='index' v-for="(item,index) in tagsPath"><span
                style="cursor: pointer" @click="handleBread(item)">{{ item.name }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="right-btn">
            <el-button type="primary" size="mini" @click="addTag" :disabled="disabled">
              新增标签
            </el-button>
            <el-button type="danger" plain size="mini" @click="batchDeleteTags" :disabled="disabled">
              批量删除
            </el-button>
            <el-radio-group v-model="radio" style="margin-left: 20px" v-show="checkboxDisabled"
                            @change="radioChange">
              <el-radio :label="1"> 全选</el-radio>
              <el-radio :label="0">反选</el-radio>
            </el-radio-group>
          </div>
          <div class="right-detail">
            <div class="right-detail-item" :key="index" v-for="(item,index) in tags">
              <el-checkbox
                v-show="checkboxDisabled"
                v-model="item.check"
              >
              </el-checkbox>
              <el-input
                placeholder="请输入标签"
                size="mini"
                maxlength="20"
                :ref="'tag_' + index"
                v-model="item.name"
                style="margin-top: 15px;  width: 70%">
                <i class="el-icon-delete"
                   style="line-height: 30px"
                   slot="suffix"
                   @click="deleteTag(item,index)"></i>
              </el-input>
            </div>
          </div>

        </tag-card>
        <tag-card v-else class="body-right">
          <div style="position: absolute;height:100%; width: 100%">
            <p style="position: absolute; top:50%;left: 25%;color: #9a9a9f;font-size: 15px">
              请选择分组查看或编辑标签
            </p>
          </div>
        </tag-card>
      </div>

      <div v-show="activeName==='template'">
        <tags-template :tagsTree="tagsTree"></tags-template>
      </div>
      <tag-card style="height: 100px " v-show="activeName==='tag'">
        <div style="text-align: center">
          <el-button type="primary" style="margin: auto" size="mini" :loading="loadingbut" @click="submit">
            保存
          </el-button>
          <el-button style="margin-left: 10px" size="mini" @click="cancel">
            取消
          </el-button>
        </div>
      </tag-card>

    </basic-container>
  </div>
</template>
<script>
import {Tree, TreeNode, BeetlesTreeList} from '@/components/basic-components/beetles-tree'
import TagsTemplate from "@/views/system/components/tagsComponent/TagsTemplate"
import {
  getSystemTags,
  getTenantTags,
  submitTenant,
  saveSystemTags
} from "@/api/system/creative_tags";
import tags from "@/util/tags";
import TagCard from "@/components/TagCard/TagCard";
import {mapGetters} from "vuex";
import {deepClone} from "../../../util/util";
import func from "../../../util/func";
import _ from 'lodash'

export default {
  name: "addCreativeTags",
  computed: {
    ...mapGetters(["userInfo", "roles"]),
  },
  components: {
    BeetlesTreeList,
    TagsTemplate,
    TagCard
  },
  props: {
    offerId: String,
    active: {
      type: String
    }
  },
  data() {
    return {
      loadingbut: false,
      radio: null,
      tagsPath: [],
      rules: {
        name: [
          {required: true, message: '请输入标签', trigger: 'blur'},
        ]
      },
      disabled: true,
      iconDeleteColor: 'blue',
      checkboxDisabled: false,
      activeName: this.active,
      currentNode: null,
      newTree: {},
      data1: null,
      tags: [],
      // 面包屑
      breadcrumb: [],
      loading: false,
      tagsTree: []
    }
  },
  watch: {
    tags: {
      handler(newTags) {
        if (this.currentNode != null) {
          this.currentNode.tags = newTags;
        }
      },
      deep: true
    }
  },
  created() {
    this.getTags();
  },
  methods: {
    closeWindow() {
      console.log('test')
      this.$parent.config = 'main'
    },
    getTags() {
      //pc端
      if (this.roles.administrator) {
        Promise.all([
          getSystemTags(),
        ]).then((result) => {
          let tagsff = result[0].data.data;
          this.tagsTree = deepClone(tagsff);
          this.data1 = new Tree(tagsff)
        });
      } else {
        Promise.all([
          getSystemTags(),
          getTenantTags()
        ]).then((result) => {
          let tagsff = tags.tagsAdd(result[0].data.data, result[1].data.data)
          this.tagsTree = deepClone(tagsff);
          this.data1 = new Tree(tagsff)
          // console.log(this.data1)
        })
      }

    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    onDel(node) {
      // console.log(node)
      this.$confirm('该分组及其子组都会被删除，删除不影响已有标签模板，是否删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        node.remove()
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },

    onChangeName(params) {
      console.log(params.newName)
    },

    onAddNode(params) {
      // console.log(params)
      return params.name
    },
    OnNodeChange(node) {
      console.log(node)
      let type = node.mode.type;
      if (type === 'system') {
        this.disabled = true;
      } else {
        this.disabled = false;
      }
      this.tagsPath = []
      this.getBreadcrumb(node.mode)
      this.tagsPath.shift()
      console.log('面包屑', this.tagsPath)
      console.log('子组')
      this.currentNode = node.mode;
      let tags = this.currentNode.tags;
      if (tags == undefined) {
        tags = [];
        this.currentNode.tags = [];
      }
      this.tags = tags;
    },
    // 生成面包屑导航
    getBreadcrumb(parent) {
      if (parent.hasOwnProperty('parent')) {
        this.tagsPath.unshift(parent)
        this.getBreadcrumb(parent.parent)
      } else {
        this.tagsPath.unshift(parent)
      }
    },
    onClick(params) {
      this.checkboxDisabled = false

    },
    addNode() {
      var node = new TreeNode({name: 'new node', showType: 'view', type: "global"})
      if (!this.data1.groups) this.data1.groups = []
      this.data1.addChildren(node)
    },

    getNewTree() {
      var vm = this

      function _dfs(oldNode) {
        var newNode = {}

        for (var k in oldNode) {
          if (k !== 'groups' && k !== 'parent' && k !== 'id' && k !== 'tags') {
            newNode[k] = oldNode[k]
          }
        }
        if (oldNode.groups && oldNode.groups.length > 0) {
          newNode.groups = []
          for (var i = 0, len = oldNode.groups.length; i < len; i++) {
            newNode.groups.push(_dfs(oldNode.groups[i]))
          }
        }
        if (oldNode.tags && oldNode.tags.length > 0) {
          newNode.tags = []
          oldNode.tags.map(item => {
            let newtags = {};
            if (!func.isEmpty(item.name)) {
              for (let k in item) {
                if (k !== 'check') {
                  newtags[k] = item[k];
                }
              }
              newNode.tags.push(newtags);
            }
          })
        }
        return newNode
      }

      vm.newTree = _dfs(vm.data1)
    },
    addTag() {
      let type = this.currentNode.type;
      if (type === 'system') {
        this.$message.error('系统标签不允许新增')
        return;
      }
      this.tags.unshift({
        name: '',
        flag: '',
        check: null
      })
      console.log('addtag', this.tags)
    },
    /**
     * 单个标签删除
     */
    deleteTag(tag, index) {
      if (this.tags != undefined && this.tags.length > index) {
        this.tags.splice(index, 1)
      }

    },
    /**
     * 批量删除素材标签
     */
    batchDeleteTags() {
      if (!this.checkboxDisabled) {
        this.checkboxDisabled = true
        return;
      }
      let temptags = [];
      if (this.tags.length > 0) {
        this.tags.forEach((item, index) => {
          if (!item.check) {
            temptags.push(this.tags[index])
          }
        })
        this.tags = temptags;
      }
    },
    delayLoading() {
      let _this = this
      setTimeout(function () {
        _this.loadingbut = false//娃娃消失
      }, 2000);
    },
    /**
     * 检查 tags ，复制loran 逻辑，紧急修复，后续修改
     * @returns {boolean}
     */
    checkTags() {
      if (this.tagsPath.length <= 0) {
        return true;
      }
      console.log('tagsPath', this.tagsPath);
      let index = this.tagsPath.length - 1
      let tagArr = this.tagsPath[index].tags;
      let tagsArr = [];
      for (let i = 0; i < tagArr.length; i++) {
        tagsArr.push(tagArr[i].name);
      }
      tagsArr.splice(0, 1)
      console.log('arr', this.tagsPath)
      console.log('name', this.tags[0].name)

      let nodeArr = this.tagsPath[index].groups
      let nodesArr = []
      for (let i = 0; i < nodeArr.length; i++) {
        nodesArr.push(nodeArr[i].name);
      }
      console.log('nodearr', nodesArr, nodesArr.length)
      let last = nodesArr[nodesArr.length - 1]
      // let nodesArr2=nodesArr.splice(nodesArr.length,1)
      console.log('last', last)
      // console.log('子组',this.tagsPath[0].groups)
      // console.log('新增组',nodesArr2)
      // console.log(tagsArr.indexOf(this.tags[0].name)>-1)
      console.log((nodesArr.indexOf(last)) < (nodesArr.length - 1))

      if ((nodesArr.indexOf(last)) < (nodesArr.length - 1)) {
        this.$message({
          type: 'warning',
          message: '标签组命名重复请重新输入'
        });
        this.loadingbut = false;
      } else {
        if ((tagsArr.indexOf(this.tags[0].name)) > -1) {

          this.$message({
            type: 'warning',
            message: '标签命名重复请重新输入，重复标签：' + this.tags[0].name + '，' + '标签组：' + this.tagsPath[index].name
          });
          this.loadingbut = false;

          this.tags.splice(0, 1)

          return false


        } else {
          tagsArr.unshift(this.tags[0].name)

        }
      }

      return true;

    },
    /**
     * 提交保存素材标签
     */
    submit() {
      // this.loadingbut = true;
      // console.log("data", this.data1)
      let node = this.getNewTree();
      // console.log(JSON.stringify(node))
      this.uniqNewTree(this.newTree.groups)

      let requestTags = JSON.stringify(this.newTree.groups);
      //调用接口保存
      //   if (!this.checkTags()){
      //     //校验不通过，不保存
      //     return
      //   }
      // pc 端保存
      if (this.roles.administrator) {
        saveSystemTags(requestTags).then(() => {
          this.delayLoading()
          this.$message.success("更新成功")
          this.getTags()
        }).finally(() => {
          this.globalEditControl = false
        })
      } else {
        submitTenant(requestTags).then(() => {
          this.delayLoading()
          this.$message.success("更新成功")
          this.getTags()
          this.tags = this.tags.filter(item => {
            if (item.name === '') {
              return false;
            }
            return true;
          })

        }).finally(() => {
          this.globalEditControl = false
        })
      }

    },
    // 去重
    uniqNewTree(arr) {
      arr.forEach(item => {
        if (item.hasOwnProperty('tags') && item.tags.length > 0) {
          console.log(item)
          item.tags = _.uniqWith(item.tags,function (a,b) {
            return a.name === b.name
          })
        }
        if (item.hasOwnProperty('groups') && item.groups.length > 0) {
          this.uniqNewTree(item.groups)
        }
      })
    },
    //取消
    cancel() {
      this.checkboxDisabled = false;
    },
    radioChange(lable) {
      //全选
      if (lable == 1) {
        if (this.tags.length > 0) {
          this.tags.forEach(item => {
            item.check = true;
          })
        }

      }
      //反选
      else if (lable == 0) {
        if (this.tags.length > 0) {
          this.tags.forEach(item => {
            item.check = !item.check;
          })
        }
      }
    },
    // 位置标签跳转
    handleBread(node) {
      this.currentNode = node
      let tags = this.currentNode.tags;
      if (tags == undefined) {
        tags = [];
        this.currentNode.tags = [];
      }
      this.tags = tags;
    }
  },

};
</script>
<style scoped>

.el-main-style {
  background-color: beige;
  padding: 2px;
  margin-left: 10px;
  line-height: 20px;

}

.el-main-style p {
  padding: 0px;
  margin: 0;
}

.el-main-style .el-breadcrumb i {
  font-size: 14px;
}

.del-icon {
  margin-left: -30px;
}
</style>

<style lang="scss" scoped>
::v-deep .el-radio-button__inner {
  padding: 7px 35px;
}

.tag-page {
  display: flex;
}

.right-path {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 30px;
}

.right-btn {
  display: flex;
  align-items: center;
}

.right-detail {
  display: grid;
  grid-template-columns: 250px 250px 250px;
  grid-gap: 10px;

  .right-detail-item {
    width: 228px;
  }
}

.body-right {
  width: 100%;

  .right-bottom {
  }
}
</style>
